const { User, Resource } = require('../models');
const cozeClient = require('../utils/cozeClient');
const eduSystemClient = require('../utils/eduSystemClient');

/**
 * 生成试卷
 * @route POST /api/paper/generate
 */
const generatePaper = async (req, res, next) => {
  try {
    const { knowledgeRange, difficultyDistribution, questionTypeRatio, userId = 1 } = req.body;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取知识点详情
    const knowledgePoints = [];
    for (const knowledgePointId of knowledgeRange) {
      const detail = await eduSystemClient.getKnowledgePointDetail(knowledgePointId);
      knowledgePoints.push(detail);
    }
    
    // 3. 构建Coze智能体输入参数
    const cozeParams = {
      knowledgePoints: knowledgePoints.map(kp => ({
        id: kp.id,
        name: kp.name,
        description: kp.description,
        difficulty: kp.difficulty,
        importance: kp.importance
      })),
      difficultyDistribution: difficultyDistribution || { easy: 0.3, medium: 0.5, hard: 0.2 },
      questionTypeRatio: questionTypeRatio || {
        choice: 0.4,
        completion: 0.3,
        shortAnswer: 0.2,
        essay: 0.1
      },
      totalScore: 100,
      examDuration: 120, // 默认120分钟
      outputFormat: 'JSON' // 请求结构化输出
    };
    
    // 4. 调用Coze智能体生成试卷
    const paperResult = await cozeClient.callBot('paperBot', cozeParams);
    
    // 5. 调用试卷校验智能体检查知识点覆盖率和重复率
    const validationParams = {
      paper: paperResult,
      knowledgePoints: knowledgePoints.map(kp => ({
        id: kp.id,
        name: kp.name
      })),
      minCoverageRate: 0.8, // 最低知识点覆盖率80%
      maxDuplicationRate: 0.1 // 最高重复率10%
    };
    
    const validationResult = await cozeClient.callBot('paperValidationBot', validationParams);
    
    // 6. 如果校验不通过，返回错误
    if (!validationResult.isValid) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: validationResult.message || '试卷生成失败，知识点覆盖率或重复率不符合要求',
        data: {
          coverage: validationResult.coverage,
          duplication: validationResult.duplication,
          issues: validationResult.issues
        }
      });
    }
    
    // 7. 保存到资源表
    const paperContent = {
      title: paperResult.title,
      sections: paperResult.sections,
      answerContent: paperResult.answerContent,
      totalScore: paperResult.totalScore || 100,
      examDuration: paperResult.examDuration || 120,
      knowledgePoints: knowledgePoints.map(kp => kp.name),
      difficultyDistribution,
      questionTypeRatio,
      coverage: validationResult.coverage,
      duplication: validationResult.duplication,
      generatedAt: new Date().toISOString()
    };
    
    const resource = await Resource.create({
      userId,
      type: 'paper',
      content: paperContent,
      isSaved: false
    });
    
    // 8. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        paperContent: {
          title: paperResult.title,
          sections: paperResult.sections,
          totalScore: paperResult.totalScore || 100,
          examDuration: paperResult.examDuration || 120
        },
        answerContent: paperResult.answerContent,
        coverage: validationResult.coverage,
        resourceId: resource.id
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 导出试卷为PDF
 * @route GET /api/paper/export/:resourceId
 */
const exportPaper = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    const { includeAnswer = true } = req.query;
    
    // 1. 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'paper'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '试卷资源不存在'
      });
    }
    
    // 2. 生成PDF（实际项目中应该调用PDF生成库）
    // 这里模拟PDF生成，返回成功消息
    
    // 模拟PDF生成延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 3. 返回结果
    res.json({
      code: 200,
      success: true,
      message: 'PDF导出功能在实际项目中实现',
      data: {
        resourceId,
        fileName: `试卷_${resourceId}${includeAnswer ? '_含答案' : ''}.pdf`,
        // 实际项目中应该返回PDF文件下载链接
        downloadUrl: `/downloads/papers/${resourceId}${includeAnswer ? '_with_answers' : ''}.pdf`
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取试卷详情
 * @route GET /api/paper/:resourceId
 */
const getPaperDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'paper'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '试卷资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resourceId: resource.id,
        userId: resource.userId,
        paperContent: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  generatePaper,
  exportPaper,
  getPaperDetail
};